Page({
  data: {
    cellArr: [],
  },
  onLoad: function () {
    this.startGame()
  },
  startGame() {
    this.setData({
      cellArr: Array.from(Array(4)).map(() => Array(4).fill(0)),
    })
    this.fillOneEmptyCell()
    this.fillOneEmptyCell()
  },
  fillOneEmptyCell() {
    const emptyCells = this.findEmptyCells()
    if (emptyCells.length > 0) {
      const [row, col] = emptyCells[this.random(emptyCells.length)]
      this.data.cellArr[row][col] = this.getRandomValue()
      this.setData({ cellArr: this.data.cellArr })
    }
  },
  getRandomValue() {
    return Math.random() < 0.9 ? 2 : 4
  },
  random(max) {
    return Math.floor(Math.random() * max)
  },
  findEmptyCells() {
    const emptyCells = []
    for (let i = 0; i < 4; i++) {
      for (let j = 0; j < 4; j++) {
        if (this.data.cellArr[i][j] === 0) {
          emptyCells.push([i, j])
        }
      }
    }
    return emptyCells
  }
})